<?php
/**
 * Created by PhpStorm.
 * User: 123
 * Date: 2020/8/10
 * Time: 10:10
 */

namespace app\service;



use EasyWeChat\Factory;
use phpmailer\BaseException;
use think\Db;

class WxService
{
    private $app;
    private $payapp;
    /**
     * [__construct 构造方法]
     * @author   juzi
     * @blog     https://i.csdn.net/#/uc/profile
     * @version  1.0.0
     * @datetime 2020年5月4日15:12:03
     * @param   [array]     $param         [所需参数]
     *
     */
    public function __construct($param)
    {
        if($param['wechat'])
        {
            $config=$this->SetAppConfig();
            $this->app = Factory::officialAccount($config);
        }

        if($param['wepay'])
        {
            $payconfig=$this->SetPayConfig();
            $this->payapp = Factory::payment($payconfig);

        }

    }

    /**
     * [GetAuthSessionKey 授权获取用户信息]
     * @author   juzi
     * @blog     https://i.csdn.net/#/uc/profile
     * @version  1.0.0
     * @datetime 2017-12-30T18:20:53+0800
     * @param    [string]     $authcode       [用户授权码]
     * @return   [string|boolean]             [失败false, 成功返回appid|]
     */
    public function GetAuthSessionKey()
    {
        $app= $this->app;
        $oauth = $app ->oauth;
        $user = $oauth->user();
        $access = $user->getAccessToken()->toArray();

        $access_token = $access['access_token'];

        $openId=$user->getId();




        if($openId)
        {
//获取用户信息
            $abs_url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$access_token."&openid=".$openId."&lang=zh_CN";

            $abs_url_data = file_get_contents($abs_url);
            $obj_data=json_decode($abs_url_data,true);
            return $obj_data;
        }

        throw new BaseException(['code'=>403 ,'errorCode'=>1016,'msg'=>'获取openid失败','status'=>false,'debug'=>false ]);



    }
    /**
     * [GetUserInfo 根据openid获取详细信息]
     * @author   juzi
     * @blog     https://i.csdn.net/#/uc/profile
     * @version  1.0.0
     * @datetime 2017-12-30T18:20:53+0800
     * @param    [string]     $openid       [用户openid]
     * @return   [string|boolean]             [失败false, 成功返回appid|]
     */
    public function GetUserInfo($openId){
        $app= $this->GetApp();
        $userinfo= $app->user->get($openId);

        //Db::table('comback')->insert(array('content'=>json_encode($userinfo)));

        if(empty($userinfo))
        {

            throw new BaseException(['code'=>403 ,'errorCode'=>1016,'msg'=>'获取userinfo失败','status'=>false,'debug'=>false ]);

        }


        $data=[
            'openid'=>$userinfo['openid'],
            'province'=>$userinfo['province'],
            'city'=>$userinfo['city'],
            'name'=>isset($userinfo['nickname'])?$userinfo['nickname']:'未获取到用户昵称',
            'headpic'=>isset($userinfo['headimgurl'])?$userinfo['headimgurl']:'http://yun.youpilive.com/static/default_avatar.png',
            'unionid'=>empty($userinfo['unionid'])?'':$userinfo['unionid'],
            'ish5'=>1,//h5授权时是1  不知道 这个方法APP 调了么
        ];

            Db::name('member')->insert($data);


    }

    /**
     * [SendTemplateMessage 发送模板消息]
     * @author   juzi
     * @blog     https://i.csdn.net/#/uc/profile
     * @version  1.0.0
     * @datetime 2017-12-30T18:20:53+0800
     * @param    [array]     $params       [所需参数]
     */
    public function SendTemplateMessage($params=[]){

        $re= $this->app->template_message->send($params);

        if($re['errcode']){
            return DataReturn([$re['errmsg'],$re['errcode']]);

        }

        return true;
    }
    /**
     * [GetApp 获取普通的微信配置]
     * @author   juzi
     * @blog     https://i.csdn.net/#/uc/profile
     * @version  1.0.0
     * @datetime 2017-12-30T18:20:53+0800
     * @return   [object]
     */
    public function GetApp(){
        return $this->app;
    }
    /**
     * [GetPayApp 获取微信支付需要的微信配置]
     * @author   juzi
     * @blog     https://i.csdn.net/#/uc/profile
     * @version  1.0.0
     * @datetime 2017-12-30T18:20:53+0800
     * @return   [object]
     */
    public function GetPayApp(){
        return $this->payapp;
    }

    private function SetAppConfig(){
        $config= [
            'app_id'  => Db::name('payapi')->where('id=3')->value('appid'),
            'secret'  => Db::name('payapi')->where('id=3')->value('appsecrt'),
            'token'  => '123456',
            'aes_key' => '',
            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',
            'log' => [
                'default' => 'prod', // 默认使用的 channel，生产环境可以改为下面的 prod
                'channels' => [
                    // 测试环境
                    'dev' => [
                        'driver' => 'single',
                        'path' => ROOT_PATH.'/log/.log',
                        'level' => 'debug',
                    ],
                    // 生产环境
                    'prod' => [
                        'driver' => 'daily',
                        'path' => ROOT_PATH.'/log/.log',
                        'level' => 'info',
                    ],
                ],
            ],
            'oauth' => [
                'scopes'   => ['snsapi_userinfo'],
                'callback' => '/api/index/wxlogin',
            ],
            'expire'=>0,
        ];
        return $config;
    }

    private function SetPayConfig(){
        $config = [
            // 必要配置
            'app_id'             => Db::name('payapi')->where('id=3')->value('appid'),
            'mch_id'             =>  Db::name('payapi')->where('id=3')->value('mch_id'),
            'key'                =>'youpi160188924116018892411601889',   // API 密钥


            'notify_url' => __MY_PUBLIC_URL__.'/api/Fee/notifyurl', // 支付结果通知网址，如果不设置则会使用配置里的默认地址

        ];

        return $config;

    }
}